package com.test.util;

/**
 * 分页类
 */
@SuppressWarnings("unchecked")
public class Pagination {

	// 缺省每页记录数
	public static final int NUMBERS_PER_PAGE = 10;

	// 缺省当前页
	public static final int CURRENT_PAGE = 1;

	// 缺省当前页
	public static final int TOTAL_ROWS = 1;

	public static final String PAGE_PARAM = "page";

	// 一页显示的记录数
	private int numPerPage;

	// 记录总数
	private int totalRows;

	// 总页数
	private int totalPages;

	// 当前页码
	private int currentPage;

	private int startPage;

	// 前页码
	private int prePage;

	// 后页码
	private int nextPage;

	private int lastPage;

	// 起始行数
	private int startIndex;

	// 结束行数
	private int lastIndex;

	public Pagination(int currentPage) {
		if (currentPage <= 0) {
			this.setCurrentPage(CURRENT_PAGE);
		} else {
			this.setCurrentPage(currentPage);
		}
		this.setNumPerPage(NUMBERS_PER_PAGE);
	}

	public Pagination(int currentPage, int numPerPage) {
		if (currentPage <= 0) {
			this.setCurrentPage(CURRENT_PAGE);
		} else {
			this.setCurrentPage(currentPage);
		}

		if (numPerPage <= 0) {
			this.setNumPerPage(NUMBERS_PER_PAGE);
		} else {
			this.setNumPerPage(numPerPage);
		}
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public int getTotalPages() {
		return totalPages;
	}

	// 计算总页数
	public void setTotalPages() {
		if (totalRows % numPerPage == 0) {
			this.totalPages = totalRows / numPerPage;
		} else {
			this.totalPages = (totalRows / numPerPage) + 1;
		}
	}

	public int getTotalRows() {
		return totalRows;
	}

	public void setTotalRows(int totalRows) {
		this.totalRows = totalRows;
		this.setTotalPages();
	}

	// 计算开始时候的索引
	public int getStartIndex() {
		this.startIndex = (currentPage - 1) * numPerPage;
		return startIndex;
	}

	// 计算结束时候的索引
	public int getLastIndex() {
		if (totalRows < numPerPage) {
			this.lastIndex = totalRows;
		} else if ((totalRows % numPerPage == 0) || (totalRows % numPerPage != 0 && currentPage < totalPages)) {
			this.lastIndex = currentPage * numPerPage;
		} else if (totalRows % numPerPage != 0 && currentPage == totalPages) {// 最后一页
			this.lastIndex = totalRows;
		}
		return lastIndex;
	}

	public int getNextPage() {
		this.setTotalPages();
		nextPage = currentPage + 1 < totalPages ? currentPage + 1 : totalPages;
		return nextPage;
	}

	public int getPrePage() {
		prePage = currentPage - 1 > 1 ? currentPage - 1 : 1;
		return prePage;
	}

	public int getStartPage() {
		return getStartIndex() == 0 ? getStartIndex() + 1 : getStartIndex();
	}

}